<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="餐馆" prop="resId">
        <el-select
            v-model="queryParams.resId"
            placeholder="请选择餐馆"
            clearable
            style="width: 200px"
        >
          <el-option
              v-for="resinfo in resinfoList"
              :key="resinfo.resId"
              :label="resinfo.resName"
              :value="resinfo.resId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="顾客" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入顾客昵称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评论星级" prop="userReviewStar">
        <el-input
          v-model="queryParams.userReviewStar"
          placeholder="请输入评论星级"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间" prop="reviewTime">
        <el-date-picker clearable
          v-model="queryParams.reviewTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 200px">
          <el-option
              v-for="dict in res_review_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:resreview:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:resreview:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="resreviewList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="排序" align="center">
        <template #default="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column label="餐馆" align="center" prop="resInfo.resName" />
      <el-table-column label="顾客" align="center" prop="nickName" />
      <el-table-column label="评论内容" align="center">
        <template #default="scope">
          <span>{{ stripHtmlTags(scope.row.content) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="评论图片" align="center">
        <template #default="scope">
          <image-preview
              v-if="scope.row.imgList && scope.row.imgList.length > 0"
              :key="scope.row.imgList[0].imgId"
              :src="scope.row.imgList[0].imgUrl"
              :width="50"
              :height="50"/>
          <div v-else>暂无评论图片</div>
        </template>
      </el-table-column>
      <el-table-column label="用户评论星级" align="center" prop="userReviewStar" />
      <el-table-column label="时间" align="center" prop="reviewTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.reviewTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="res_review_type" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:resreview:edit']">详情</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:resreview:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改餐馆评论对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="resreviewRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="餐馆" prop="resId">
          <el-select v-model="form.resInfo.resName" placeholder="请选择状态" @change="handleresInfoChange">
            <el-option
                v-for="resinfo in resinfoList"
                :key="resinfo.resId"
                :label="resinfo.resName"
                :value="resinfo.resId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="顾客" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入顾客昵称" />
        </el-form-item>
        <el-form-item label="评论内容">
          <editor v-model="form.content" :min-height="122"/>
        </el-form-item>
        <el-form-item label="评论图片">
          <div v-if="form.imgList && form.imgList.length > 0">
            <image-preview
                v-for="img in form.imgList"
                :key="img.imgId"
                :src="img.imgUrl"
                :width="50"
                :height="50"/>
          </div>
          <div v-else>暂无评论图片</div>
        </el-form-item>
        <el-form-item label="口味星级" prop="tasteStar">
          <el-input v-model="form.tasteStar" placeholder="请输入口味星级" />
        </el-form-item>
        <el-form-item label="服务星级" prop="serviceStar">
          <el-input v-model="form.serviceStar" placeholder="请输入服务星级" />
        </el-form-item>
        <el-form-item label="环境星级" prop="environmentStar">
          <el-input v-model="form.environmentStar" placeholder="请输入环境星级" />
        </el-form-item>
        <el-form-item label="评论星级" prop="userReviewStar">
          <el-input v-model="form.userReviewStar" placeholder="请输入用户评论星级" />
        </el-form-item>
        <el-form-item label="时间" prop="reviewTime">
          <el-date-picker clearable
            v-model="form.reviewTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
                v-for="dict in res_review_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Resreview">
import {
  listResreview,
  getResreview,
  delResreview,
  addResreview,
  updateResreview, listResreview1
} from "@/api/system/resreview"

import {parseTime} from "../../../utils/ruoyi.js";
import {onMounted, ref} from "vue";
import {listResinfo} from "@/api/system/resinfo.js";

import useUserStore from "@/store/modules/user.js";

const userStore = useUserStore()
console.log(userStore)

const { proxy } = getCurrentInstance()
const { res_review_type } = proxy.useDict('res_review_type')

const resreviewList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const resinfoList = ref([])

// 添加去除HTML标签的函数
const stripHtmlTags = (html) => {
  if (!html) return '';
  // 创建临时div元素
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  // 返回纯文本内容
  return tempDiv.textContent || tempDiv.innerText || '';
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    resId: null,
    customerId: null,
    content: null,
    tasteStar: null,
    serviceStar: null,
    environmentStar: null,
    userReviewStar: null,
    reviewTime: null,
    status: null,
    field: null,
    nickName: null,
    resInfo: {
      resId: null,
      resName: null,
      avgPrice: null,
      address: null,
      imgUrl: null,
      groupBuyCount: null,
      serviceTel: null,
      resDesc: null,
      userId: null,
      status: null,
      province: null,
      city: null,
      district: null,
      categoryId: null,
      notice: null,
      overallScore: null,
      field: null
    },
    imgList: [] // 添加 imgList 属性
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询餐馆评论列表 */
function getList() {
  loading.value = true
  const userId = userStore.id;
  console.log('userId:', userId)
  if (userId && userId !== 1) {
    listResreview1(queryParams.value, userId).then(response => {
      resreviewList.value = response.rows
      total.value = response.rows.length
      loading.value = false
      console.log('resreviewList:', resreviewList)
    })
  }else {
    console.log('queryParams.value:', queryParams.value)
    listResreview(queryParams.value).then(response => {
      resreviewList.value = response.rows
      total.value = response.rows.length
      loading.value = false
      console.log('resreviewList:', resreviewList)
    });
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    reviewId: null,
    resId: null,
    customerId: null,
    content: null,
    tasteStar: null,
    serviceStar: null,
    environmentStar: null,
    userReviewStar: null,
    reviewTime: null,
    status: null,
    field: null,
    resInfo: {
      resId: null,
      resName: null,
      avgPrice: null,
      address: null,
      imgUrl: null,
      groupBuyCount: null,
      serviceTel: null,
      resDesc: null,
      userId: null,
      status: null,
      province: null,
      city: null,
      district: null,
      categoryId: null,
      notice: null,
      overallScore: null,
      field: null
    },
    imgList: [] // 添加 imgList 属性
  }
  proxy.resetForm("resreviewRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.reviewId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加餐馆评论"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _reviewId = row.reviewId || ids.value
  getResreview(_reviewId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "评论详情"
  })
}

function handleresInfoChange(newValue) {
  form.value.resId = newValue
  // 同时更新 resCategory 对象中的 categoryId
  form.value.resInfo.resId = newValue
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["resreviewRef"].validate(valid => {
    if (valid) {
      if (form.value.reviewId != null) {
        updateResreview(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addResreview(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _reviewIds = row.reviewId || ids.value
  proxy.$modal.confirm('是否确认删除餐馆评论编号为"' + _reviewIds + '"的数据项？').then(function() {
    return delResreview(_reviewIds)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/resreview/export', {
    ...queryParams.value
  }, `resreview_${new Date().getTime()}.xlsx`)
}

onMounted(() => {
  const userId = userStore.id;
  if (userId && userId !== 1) {
    listResinfo({userId}).then(response => {
      resinfoList.value = response.rows
    })
  }else {
    listResinfo().then(response => {
      resinfoList.value = response.rows
    })
  }
})

getList()
</script>
